import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import '../../repository/api.dart';
import '../../route/route_utils.dart';
import '../../theme.dart';
import '../auth/auth_vm.dart';
import '../auth/login_page.dart';

/// 重置密码页面
class SavepasswordPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SavepasswordState();
  }
}

class _SavepasswordState extends State<SavepasswordPage> {
  final TextEditingController _password =
      TextEditingController(text: "");
  final TextEditingController _savepaddword =
      TextEditingController(text: "");

  @override
  void initState() {
    super.initState();
    _password.addListener(_onTextChanged);
    _savepaddword.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _password.removeListener(_onTextChanged);
    _savepaddword.removeListener(_onTextChanged);
    super.dispose();
  }

  void _onTextChanged() {
    setState(() {});
  }

  Future<bool> savepadd() async {
    dynamic callback = await Api.instance
        .savepass(oldPassword: _password.text, newPassword: _savepaddword.text);
    if (callback is bool) {
      return callback;
    } else {
      return true;
    }
  }

  // 重置密码
  void _register() {
    AuthViewModel viewModel = AuthViewModel();

    // 正则表达式：至少包含一个数字和一个字母，且长度大于6位
    final RegExp usernameRegex =
        // RegExp(r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]{7,}$');
    RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$');

    if (!usernameRegex.hasMatch(_password.text)) {
      showToast("密码必须大于6位，且包含数字和字母");
      return;
    }

    if (!usernameRegex.hasMatch(_savepaddword.text)) {
      showToast("新密码必须大于6位，且包含数字和字母");
      return;
    }

    // String passwordss = AESEncryption.encrypt(_savepaddword.text);
    //
    // LogUtils.w(passwordss);


    savepadd().then((value) => {
          if (value)
            {
              RouteUtils.pushAndRemoveUntil(context, LoginPage()),
              LogUtils.w("修改密码成功"),
            }
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(left: 30, right: 30),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 40),
              Container(
                alignment: Alignment.centerLeft, // 设置容器内容左对齐
                child: Text(
                  "重置密码",
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    fontFamily: "PingFang SC, PingFang SC",
                  ),
                ),
              ),
              SizedBox(height: 30),
              // 验证码输入框

              TextField(
                controller: _password,
                decoration: InputDecoration(
                  hintText: "原密码",
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                  suffixIcon: _password.text.isNotEmpty // 当输入框有值时显示叉按钮
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _password.clear(); // 清空输入框的值
                          },
                        )
                      : null,
                ),
                cursorColor: Color(0xFF00c888),
              ),

              const SizedBox(height: 15),
              TextField(
                controller: _savepaddword,
                decoration: InputDecoration(
                  hintText: "新密码",
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                  suffixIcon: _savepaddword.text.isNotEmpty // 当输入框有值时显示叉号
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _savepaddword.clear(); // 清空输入框的值
                          },
                        )
                      : null,
                ),
                cursorColor: Color(0xFF00c888),
              ),
              SizedBox(height: 8),

              Transform.translate(
                offset: Offset(-32, 0), // 向左偏移 15
                child: Text(
                  "密码必须包含数字和字母，且长度超过8位",
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFcccccc),
                  ),
                ),
              ),

              const SizedBox(height: 30),
              // 注册
              _buildRegionButton(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
            ],
          ),
        ),
      ),
    );
  }

  // 注册
  Widget _buildRegionButton() {
    return SizedBox(
      width: 400, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: _register,
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '重置密码',
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }
}
